package com.xinfan.io.fileoutputstream;

import org.junit.jupiter.api.Test;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @Author xin
 * @Date 2022/6/8 11:42
 * @Version 1.0
 */
public class FileOutputStream_ {


    @Test
    public void write1() {
        String out = "hello000 world";

        String filename = "G:\\桌面\\out.txt";
        FileOutputStream fileOutputStream = null;

        File file = new File(filename);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        try {
            fileOutputStream = new FileOutputStream(file);//新的内容会覆盖原来的内容
            //fileOutputStream = new FileOutputStream(file,true);以追加的方式添加
            /*char[] chars = out.toCharArray();
            for (int i = 0; i < chars.length; i++) {
                fileOutputStream.write(chars[i]);

            }*/

            fileOutputStream.write(out.getBytes());
            // void write(byte[] b, int off, int len)
            //将指定 byte 数组中从偏移量 off 开始的 len 个字节写入此文件输出流。
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
